<?php
/**
 *  Generic Default Model: a class for item-based model management:
 *      - the data source is the DB
 *      - the record properties are taken from Module config
 *  Similar to Active Record pattern, in which the record is implemented in Item,
 *      and the data access in Action.
 *
 *  @todo select item externally ? or leave it up to subclass only
 *
 */
namespace Yz\modules\Generic;

class Model_List
    extends Model_Abstract
{


    /************************************
     *          Public methods          *
     ************************************/


    /**
     *  fetch hash of all items in table, indexed by id
     *  @return Yz_Hash[Yz_Item_Interface]
     *  @throw NotFound
     */
    public function fetchList()
    {
        debug();
        $action = $this->selectAction('SelectList');
        return $this->_fetch($action);
    }

    /**
     *  fetch hash of items indexed by id, using pagination
     *  @param Yz_Pagination_Interface
     *  @return Yz_Hash[Yz_Item_Interface]
     *  @throw NotFound
     */
    public function fetchPage(\Yz_Pagination_Interface $pagination)
    {
        debug();
        $action = $this->selectAction('SelectList');
        $action
            ->setOffset($pagination->getPageOffset())
            ->setLimit($pagination->getPageItems())
        ;
        $list = $this->_fetch($action);
        $pagination->setItemCount($action->getFoundRows());
        return $list;
    }

    /************************************
     *       Protected methods          *
     ************************************/

    /** create a list of items and assign values to them
     *  @param hash
     *  @param item template item
     *  @return hash{item}
     */
    protected function assignValues($values, $item)
    {
        if (null === $values) {
            return new \Yz_Hash();
        }
        ### new: a result indexed by IDs can not be an Array, it is physically a hash
        $list = array();
        foreach ($values as $value) {
            $item0 = clone $item;
            $list[$value->id] = $item0->assignValues($value);
        }
        return new \Yz_Hash($list);
    }


}
